﻿using MvcWechat.Common;
using MvcWechat.Cryptography;
using MvcWechat.ServiceReference1;
using MvcWechat.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;

namespace MvcWechat.Controllers
{

    public class WebController : CustomerController
    {

        RetailClient service = new RetailClient();
        //
        // GET: /Web/
        //首页
        public ActionResult Index()
        { 
            return CheckView();
        }
        //品牌
        public ActionResult Brand()
        {
            return CheckView();
        }
        //帮助
        public ActionResult Help()
        {
            return CheckView();
        }
        //钻石分级
        public ActionResult Grading()
        {
            return CheckView();
        }     //联系我们
        public ActionResult Contact()
        {
            return CheckView();
        }

        public ActionResult Address()
        {
            return CheckView();
        }
        public ActionResult OrderConfirm()
        {
            GetPostParam();
            return CheckView();
        }
    
        private ActionResult CheckView()
        {
            if (Session["CustomerID"] == null)
            {
                GetWechatLoginParam();
            }
            else
            {
                ViewBag.IsWechatLogin = false;
            }
            {
                string key = CommonPage.getKey();
                //供应商的KEY 包含下划线就标识二级 一级的KEY 不能有下划线
                if (key.Contains("__"))
                    ViewBag.IsHideSupplier = "2";
                else
                    ViewBag.IsHideSupplier = "1";
            }
            string viewName = RouteData.Values["action"].ToString();
            if (viewName.ToLower() == "white" || viewName.ToLower() == "cart" || viewName.ToLower() == "order")
            { 
            //祼钻1   2	统包全局倍率  3	成品全局倍率  4	彩宝全局倍率  5	翡翠全局倍率   6	素金全局倍率
                GetViewBagFilterFieldsByTag(1);
            }
            if (HttpContext.Session["CustomerID"] != null)
            {
                ViewBag.CustomerID = HttpContext.Session["CustomerID"];
            }
            else {
                ViewBag.CustomerID = "";
            }
            //if (config == null)
            //{
            //    config = CommonPage.GetConfigSettings();
            //}
            //ViewBag.Menus = config.Menus;

            return View(viewName);

        }
    
        //翡翠 
        public ActionResult Emerald()
        {
            return CheckView();
        }
        //翡翠订单 
        public ActionResult EmeraldOrder()
        {
            return CheckView();
        }
        //翡翠购物车 
        public ActionResult EmeraldCart()
        {
            return CheckView();
        }
        

        ////客户登录 10-27
        public ActionResult Login()
        {
            //ViewBag.IsHideWechatLogin = (CommonPage.SuppplierAllKey[CommonPage.getKey()].AppIDByWechatLogin != "" && CommonPage.SuppplierAllKey[CommonPage.getKey()].AppSecretByWechatLogin != "");
         
            ManagerSession.RemoveSession("CustomerID");
            return CheckView();
        }

        private void GetWechatLoginParam()
        {
            ConfigSettings config = CommonPage.GetConfigSettings();
            //是否包含微信扫码登录
            if (config != null && !string.IsNullOrEmpty(config.AppIDByWechatLogin))
            {
                ViewBag.AppId = config.AppIDByWechatLogin;
                if (ViewBag.AppId != "")
                {
                    ViewBag.IsWechatLogin = true;
                }
                else
                {
                    ViewBag.IsWechatLogin = false;
                }
                var expirationTime = DateTime.Now;
                //过期的时间 
                expirationTime = expirationTime.AddMinutes(2);
                var expirationTimekey = expirationTime.ToString("yyyy-MM-dd HH:mm:ss");
                var encode = WXBizMsgCrypt.Encrypt(expirationTimekey);
                encode = Convert.ToBase64String(Encoding.UTF8.GetBytes(encode)).TrimEnd('=');
                ViewBag.State = encode;
            }
            else
            {
                ViewBag.IsWechatLogin = false;
            }
        }

        //注册
        public ActionResult Reg()
        {
            return CheckView();
        }

        //消费记录
        public ActionResult Pay()
        {
            return CheckView();
        }

        //修改密码
        public ActionResult Pwd()
        {
            return CheckView();
        }

        //忘记密码，第一步：验证， 第二步：新密码
        public ActionResult Forgot()
        {
            return CheckView();
        }

        //在线库存
        public ActionResult Inventory()
        {
            return CheckView();
        }

        //我的订单
        public ActionResult Order()
        {
            return CheckView();
        }

        //框架
        public ActionResult Frame()
        {
            return CheckView();
        }

        //白钻
        public ActionResult White()
        {  
            return CheckView();
        }

        //彩钻
        public ActionResult Fancy()
        {
            return CheckView();
        }


        //白色统包 WhiteParcel
        public ActionResult WhiteParcel()
        {
            return CheckView();
        }

        //彩色统包 FancyParcel
        public ActionResult FancyParcel()
        {
            return CheckView();
        }

        //统包购物车
        public ActionResult ParcelCart()
        {
            return CheckView();
        }

        //统包订单
        public ActionResult ParcelOrder()
        {
            return CheckView();
        }

        //成品 Ring
        public ActionResult Ring()
        {
            return CheckView();
        }

        //成品购物车
        public ActionResult RingCart()
        {
            return CheckView();
        }

        //成品订单
        public ActionResult RingOrder()
        {
            return CheckView();
        }

        //款式 Style
        public ActionResult Style()
        {
            return CheckView();
        }

        //购物车列表
        public ActionResult Cart()
        {
            return CheckView();
        }

        //我的资料
        public ActionResult Info()
        {
            return CheckView();
        }

        //发布中公告
        public ActionResult NoticeList()
        {
            return CheckView();
        }


        //公告详情
        public ActionResult NoticeDetail()
        {
            return CheckView();
        }

        //彩宝
        public ActionResult Gems()
        {
            return CheckView();
        }
        public ActionResult GemsOrder()
        {
            return CheckView();
        }
        public ActionResult GemsCart()
        {
            return CheckView();
        }

   
  
        public ActionResult Articles()
        {
            return CheckView();
        }
        public ActionResult StocksDetail(string id)
        { 
            var param = "{\"ID\":[\"" + id + "\"]}";
            var result = service.GetInventoryInfos(param,"");
            ViewBag.RingDetail = result; 
            return CheckView();
        }
        public ActionResult GemsDetail(string id, string u)
        {
            ViewBag.GemsDetail = AddInputJsonAndGetProductData(id, 4, u);
            return CheckView(); 
        }
        public ActionResult ParcelDetail(string id, string u)
        {
            ViewBag.ParcelDetail = AddInputJsonAndGetProductData(id, 2, u);
            return CheckView();
             
        }
        public ActionResult RingDetail(string id,string u)
        {
            ViewBag.RingDetail = AddInputJsonAndGetProductData(id, 3, u);
            return CheckView(); 
            
        }
        public ActionResult EmeraldDetail(string id, string u)
        {
            ViewBag.EmeraldDetail = AddInputJsonAndGetProductData(id, 5, u);
            return CheckView();
            
        }
        public ActionResult PrimeGoldsDetail(string id, string u)
        {
            ViewBag.PrimeGoldsDetail = AddInputJsonAndGetProductData(id, 6, u);
            return CheckView();

        }
        public ActionResult OrderEdit()
        {
            GetViewBagFilterFieldsByTag(3);
            GetPostParam();
            return CheckView();
        }
        public ActionResult JewelryInstitute()
        {
            return CheckView();
        }

        #region 空托 
        public ActionResult InlaySettings()
        {
            return CheckView();
        }
        public ActionResult InlaySettingsDetail(string id, string u)
        {
            //var param = "{\"ID\":" + id + ",\"GoodsType\":7}"; 
            ViewBag.InlaySettingDetail = AddInputJsonAndGetProductData(id, 7,u);
            return CheckView(); 
        }

        private string AddInputJsonAndGetProductData(string id,int typeid,string u="")
        {
            //typeid=1为裸钻
            Dictionary<string, object> dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(GetParentKeyInputJson());
            dict.Add("ID", id); 
            if (typeid > 1) //裸钻不加入goodsType
            {
                dict.Add("GoodsType", typeid);
            }
            if (!string.IsNullOrEmpty(u))
                dict.Add("CustomerID", u);
            var param = JsonConvert.SerializeObject(dict); 
            var result = string.Empty;
            if (typeid>1)
                result = service.GetProductData(param,"");
            else
                result = service.GetInventoryInfos(param, CommonPage.getKey());// var param = "{\"ID\":[\"" + id + "\"]}"; 
            return result;
 
        }

        public ActionResult InlaySettingsOrder()
        {
            return CheckView();
        }
        public ActionResult InlaySettingsEdit()
        {
            GetViewBagFilterFieldsByTag(7);
            GetPostParam();
            return CheckView();
        }
        #endregion
        //tag  1.祼钻   2统包全局倍率  3成品全局倍率  4	彩宝全局倍率  5	翡翠全局倍率   6	素金全局倍率  7空托
        public void GetViewBagFilterFieldsByTag(int tag)
        {
            //string viewName = RouteData.Values["action"].ToString();
            //var filterFields = service.GetGlobals(JsonConvert.SerializeObject(new { Ids = new int[] { tag } }));
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("Ids", new int[] { tag });
 
            var filterFields = service.GetGlobals(GetInputJson(dict: dict)); 
            FilterFieldsResult root = JsonConvert.DeserializeObject<FilterFieldsResult>(filterFields);
            if (root.msgcode)
            { 
                if (root.msginfo[0].FilterFields!="") 
                {
                    ViewBag.FilterFields = root.msginfo[0].FilterFields;
                }
                else
                {
                    ViewBag.FilterFields = "";
                    //return View(viewName);
                }  
            }  
        }
        public ActionResult Test()
        {
           
            return CheckView();
        }
        public ActionResult WechatLogin()
        { 
            //Logger.Debug(this.GetType(), DateTime.Now + "Run  HttpContext.Request.QueryString:" + HttpContext.Request.QueryString);
            var state = HttpContext.Request.QueryString["state"]; //这个可能只有部分参数， 如 &state=hbIC1SIRojHmLAFrUc/2zVcanJ3&amp;nbsp;Lkxg 需要再进一步处理
            if (string.IsNullOrEmpty(state))
            {
                return Content("参数不正确");
            }
            else
            {
                //var url=HttpContext.Request.QueryString.ToString();
                //var tKey = "state="; //要截取的key 此处不能直接调用 state这个变量，因为可能url中/ + 等编码了
                //state = url.Substring(url.LastIndexOf(tKey) + tKey.Length);
                state = Encoding.UTF8.GetString(Convert.FromBase64String(state.PadRight(state.Length + 1, '=')));
                var expirationTime = WXBizMsgCrypt.Decrypt(state); 
                DateTime.TryParse(expirationTime, out DateTime d);

                if (d.CompareTo(DateTime.Now) >= 0)
                {
                    var code = HttpContext.Request.QueryString["code"];
                    ConfigSettings config = CommonPage.GetConfigSettings();
                    //拿用户参数
                    var accessTokenDynamic = BasicAPI.GetAccessTokenByWechatLogin(config.AppIDByWechatLogin, config.AppSecretByWechatLogin, code);
                    if (accessTokenDynamic.access_token == "errcode")
                        return Content("参数不正确！");
                    else {
                        var accessToken = accessTokenDynamic.access_token;
                        var openId = accessTokenDynamic.openid;
                        Logger.Info(this.GetType(), $"WechatLogin,openid:{openId},accessToken:{accessToken}");
                        var weixinInfo = BasicAPI.GetUserInfoByWechatLogin(accessToken, openId);
                        Logger.Info(this.GetType(), $"WechatLogin,weixinInfo:{JsonConvert.SerializeObject(weixinInfo)}");
                        var key = CommonPage.getKey(); //url 标识
                        var v = BasicAPI.AddUserInfo(key,weixinInfo,1);
                        Logger.Info(this.GetType(), string.Format("13,添加公众号用户:{0}", v));
                        if (v) {
                            //
                            Dictionary<string,string> dictLoginParam=new Dictionary<string,string>();
                            dictLoginParam.Add("Name",openId);
                            dictLoginParam.Add("Pwd",openId);
                            dictLoginParam.Add("ActiveIP",HttpContext.Request.UserHostAddress);
                            dictLoginParam.Add("TagKey", key);
                            var islogin= CustomerLoginByWechatLogin(JsonConvert.SerializeObject(dictLoginParam));
                            if (islogin) 
                            {
                                return Redirect("~/web/index");
                            }
                            else
                                return Content("参数不正确!");
                        }
                    }
                    //登录

                    return Content("参数正确");
                }
                else
                {
                    return Content("参数过期");
                }
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////                                                            页面和方法分割线                                                             ////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
     
  
        //客户-方法

        ///// <summary>
        ///// 微信登录
        ///// </summary>
        ///// <returns></returns>
        public bool CustomerLoginByWechatLogin(string customerLoginJson)
        { 
            ManagerSession.RemoveSession("CustomerID");  

            bool isLogin = false;
            try
            {
                string customerLoginResult = service.CustomerLogin(customerLoginJson);
                Dictionary<string, object> param = ManagerJson.Deserialize<Dictionary<string, object>>(customerLoginResult); //Json转字典  
                isLogin=Convert.ToBoolean(param["msgcode"]);
                //登录成功,建立缓存
                if (isLogin)
                {
                    Dictionary<string, object> customerParam = ManagerJson.Deserialize<Dictionary<string, object>>(param["msginfo"].ToString());
                    ManagerSession.SetSession("CustomerID", customerParam["CustomerID"]);
                    ManagerSession.SetSession("CustomerName", customerParam["NickName"]);
                }

                return isLogin;//Wcf的CustomerLogin方法
            }
            catch (Exception ex)
            {

                return isLogin;
            }
        }

        

        

        /// <summary>
        /// 在线库存总数
        /// </summary>
        /// <returns></returns>
        public JsonResult GetInventoryInfosCount()
        {
            

            string inventoryJson = GetInputJson();

            try
            {
                return Json(service.GetInventoryInfosCount(inventoryJson));
                // return Json(1);
            }
            catch (Exception ex)
            {
                return Json("程序内部错误，请调试程序。" + ex.Message);
            }
        }
        /// <summary>
        /// 我的订单
        /// </summary>
        /// <returns></returns>
        public JsonResult GetOrders()
        {
            

            string ordersJson = GetInputJson();

            return Json(service.GetOrders(ordersJson));
        }

        /// <summary>
        /// 购物车列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCartInfos()
        {
            

            string cartsJson = GetInputJson();

            return Json(service.GetCartInfos(cartsJson));
        }
        /// <summary>
        /// 购物车列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCartsCount()
        { 

            string cartsJson = GetInputJson();

            return Json(service.GetCartsCount(cartsJson));
        }

        ///// <summary>
        ///// 客户注册
        ///// </summary>
        ///// <returns></returns>
        //public JsonResult CustomerRegister()
        //{
        //    

        //    string customerRegisterJson = SerializeObject(true);

        //    return Json(service.CustomerRegister(customerRegisterJson));
        //}
        /// <summary>
        /// 客户删除购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult DeleteAllCart()
        {
            

            string customerRegisterJson = GetInputJson(true);

            return Json(service.DeleteCart(customerRegisterJson));
        }
        /// <summary>
        /// 帐号是否已存在
        /// </summary>
        /// <returns></returns>
        public JsonResult CustomerRegIsExist()
        {
            string customerRegIsExistJson = GetInputJson();
            return Json(service.CustomerRegIsExist(customerRegIsExistJson));
        }

        /// <summary>
        /// 加入购物车(仅单个)
        /// </summary>
        /// <returns></returns>
        public JsonResult AddToCart()
        {
           

            string addToCartJson = GetInputJson(true);

            return Json(service.AddToCart(addToCartJson));
        }

        /// <summary>
        /// 加入购物车(多个和单个)
        /// </summary>
        /// <returns></returns>
        public JsonResult MultiAddToCart()
        {
            

            string mulitAddToCartJson = GetInputJson(true);

            return Json(service.MultiAddToCart(mulitAddToCartJson));
        }


        /// <summary>
        /// 移除购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult RemoveFromCart()
        {
            

            string removeFromCartJson = GetInputJson(true);

            return Json(service.RemoveFromCart(removeFromCartJson));
        }

        ///// <summary>
        ///// 提交订单(购物车结算)
        ///// </summary>
        ///// <returns></returns>
        //public JsonResult SubmitOrder()
        //{
        //    string submitOrderJson = GetInputJson(true); 
        //    return Json(service.SubmitOrder(submitOrderJson));
        //}

        ///// <summary>
        ///// 客户资料
        ///// </summary>
        ///// <returns></returns>
        //public JsonResult GetCustomerInfo()
        //{
            

        //    string getCustomerInfoJson = GetInputJson();

        //    return Json(service.GetCustomerInfo(getCustomerInfoJson));
        //}

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        //public JsonResult CustomerModifyPassword()
        //{
        //    

        //    string customerModifyPasswordJson = SerializeObject(true);

        //    return Json(service.CustomerModifyPassword(customerModifyPasswordJson));
        //}

        

         


        /// <summary>
        /// 发布中公告
        /// </summary>
        /// <returns></returns>
        public JsonResult GetNoticeList()
        {
            

            string getNoticeListJson = GetInputJson();


            return Json(service.GetNoticeList(getNoticeListJson));
        }


         


        //////////////////以下为Ring方法////////////////////////////////////

        //成品列表
        public JsonResult GetInlays()
        {
            

            string getInlaysJson = GetInputJson();

            return Json(service.GetInlays(getInlaysJson));
        }

        
        //添加预约进店
        public JsonResult AddAppointment()
        {
            

            string getInlaysJson = GetInputJson();

            return Json(service.AddAppointment(getInlaysJson));
        }
    

        ////成品列表
        //public JsonResult GetBrand()
        //{
        //    
        //    string getInlaysJson = GetInputJson();
        //    return Json(service.GetInlays(getInlaysJson));
        //}



        //protected override ITempDataProvider CreateTempDataProvider()
        //{
        //    //return new Microsoft.Web.Mvc.CookieTempDataProvider(this.HttpContext);
        //    return new MvcWechat.Common.CookieTempDataProvider(this.HttpContext);
        //}

    } 
    public class FilterFieldsResult
    {
        public bool msgcode { get; set; }
        public List<FilterFieldsClass> msginfo { get; set; }
    }
    public class FilterFieldsClass
    {
        public int SysSettingID { get; set; }
        public int CurrentSet { get; set; }
        public double Rate { get; set; }
        public double PurchaseExchangerate { get; set; }
        public double GlobalDiscountReturn { get; set; }
        public double GlobalFancyDiscountReturn { get; set; }
        public string Notice { get; set; }
        public DateTime UpdateTime { get; set; }
        public string Group4C { get; set; }
        public string GroupFancy4C { get; set; }
        public string GroupAmount { get; set; }
        public string FilterFields { get; set; }
    } 
}
